<template>
  <div id="versionSetting">
    <h1 class="title">版本发布</h1>
    <div class="main-cont">
      <v-toolbar @click="creatPack" :buttonsObj="btnName" style="margin:0 0 10px 0"></v-toolbar>
      <div class="table-cont">
        <el-table :data="tableData">
          <el-table-column type="expand">
            <template slot-scope="props">
              <el-form label-position="left" inline class="demo-table-expand">
                <el-form-item label="版本名称：">
                  <span>{{ props.row.ClientVersionName }}</span>
                </el-form-item>
                <el-form-item label="提示信息：">
                  <span>{{props.row.HintMessage}}</span>
                </el-form-item>
                <el-form-item label="发布描述：">
                  <span>{{props.row.PublishDescription}}</span>
                </el-form-item>
                <el-form-item label="用户组名：">
                  <span>{{props.row.UserGroupName}}</span>
                </el-form-item>
                <el-form-item label="创建时间：">
                  <span v-if="props.row.CreateTime">{{props.row.CreateTime | capitalize}}</span>
                </el-form-item>
              </el-form>
            </template>
          </el-table-column>
          <el-table-column label="系统类型" prop="ClientType">
            <template slot-scope="props">
              <span>{{props.row.ClientType === '0' ? 'Android' : 'Ios'}}</span>
            </template>
          </el-table-column>
          <el-table-column label="版本号" prop="ClientVersionId"></el-table-column>
          <!-- <el-table-column label="发布类型">
            <template slot-scope="props">
              <span v-if="props.row.PublishType">{{ props.row.PublishType === '1' ?  '灰度发布' : '正式发布'}}</span>
              <span v-else>待发布</span>
            </template>
          </el-table-column> -->
           <el-table-column label="发布类型">
            <template slot-scope="props">
              <span v-if="props.row.PublishType">{{ props.row.PublishType | publishT}}</span>
              <span v-else>待发布</span>
            </template>
          </el-table-column>
          <el-table-column label="是否强制">
            <template slot-scope="props">
              <span v-if="props.row.IsForceUpdate">{{ props.row.IsForceUpdate === '0' ?  '是' : '否'}}</span>
              <span v-else>待发布</span>
            </template>
          </el-table-column>
          <el-table-column label="二维码">
            <template slot-scope="scope">
              <el-popover placement="top" trigger="hover">
                <canvas :id="scope.row.ClientVersionId"></canvas>
                <img slot="reference" @mouseenter="createQrc(scope.row.ClientVersionId, scope.row.ClientVersionURL)" src="../../../../images/qrcode.png" style="width: 15px; height: 15px" alt="这是一张icon图标">
              </el-popover>
            </template>
          </el-table-column>
          <el-table-column label="发布时间" align="center">
            <template slot-scope="scope">
              <span v-if="scope.row.PublishTime">{{scope.row.PublishTime | capitalize}}</span>
              <!-- <span></span> -->
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <!-- <template slot-scope="props" v-if="props.row.IosFlag !== undefined">
              <el-button @click="creatPublishTasks(props.row)" type="text" size="mini">发布</el-button>
              <el-button type="text" size="mini" @click="delVersion(props.row)">删除</el-button>
            </template> -->
            <template slot-scope="props">
              <el-button @click="creatPublishTasks(props.row)" type="text" size="mini">发布</el-button>
              <el-button type="text" size="mini" @click="delVersion(props.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <!--添加发布包-->
    <el-dialog title="新增版本" :visible.sync="packVisible" @close="addPublishCloseDialog">
      <el-form :model="addPublishPack" :rules="addPubsishPackRules" ref="addpg" label-position="right" label-width="130px" class="dialog-main dialogForm">
        <el-form-item label="平台 :">
          <el-radio-group v-model="sysType" size="mini">
            <el-radio-button label="Android"></el-radio-button>
            <el-radio-button label="iOS"></el-radio-button>
          </el-radio-group>
        </el-form-item>
        <!-- Android -->
        <template v-if="sysType === 'Android'">
          <el-row>
            <el-col :span="12">
              <el-form-item label="上传文件" prop="fileListForA" ref='fileForm'>
                <el-upload
                  :data="addPublishPack"
                  ref="upload"
                  action="/iap/versioncreate"
                  name="file"
                  :file-list="fileListForA"
                  :on-success="successUpload"
                  :on-change="uploadChangeA"
                  :auto-upload="false">
                  <el-button type="primary" size="mini">选择文件</el-button>
                </el-upload>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item label="新版本号" prop="ClientVersionId">
                <el-input autocomplete="off" placeholder='请输入新的版本号' v-model="addPublishPack.ClientVersionId" size="mini"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="新版本名称" prop="ClientVersionName">
                <el-input autocomplete="off" placeholder='请输入新的版本名称' v-model="addPublishPack.ClientVersionName" size="mini"/>
              </el-form-item>
            </el-col>
          </el-row>
        </template>
        <!-- iOS -->
        <template v-else>
          <el-form-item label="发布类型">
            <el-radio-group v-model="versionType">
              <el-radio label="正式版"></el-radio>
              <el-radio label="企业版"></el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="发布包" prop="fileListForI" ref="fileForm">
            <el-upload
              action="/iap/versioncreate"
              :data="addPublishPack"
              ref="upload"
              name="file"
              :file-list="fileListForI"
              :on-success="successUpload"
              :on-change="uploadChangeI"
              :auto-upload="false">
              <el-button type="primary" size="mini">选择文件</el-button>
            </el-upload>
          </el-form-item>
          <el-form-item label="版本号" prop="versionNum">
            <el-input autocomplete="off"/>
          </el-form-item>
          <template v-if="versionType === '正式版'">
            <el-form-item label="appstore地址" prop="iosPublishPackUrl">
              <el-input type="text" v-model="iosPublishPackUrl" size="mini">
                <template slot="prepend">https://itunes.apple.com/</template>
              </el-input>
            </el-form-item>
          </template>
        </template>
          <div class="form-buttons">
            <el-button @click="addPublishCloseDialog" size="mini">关闭</el-button>
            <el-button type="primary" @click="addSubmitForm" size="mini">确定</el-button>
          </div>
      </el-form>
    </el-dialog>
    <!-- 创建发布任务弹框 -->
    <el-dialog title="创建发布任务" :visible.sync="publishVisible" @close="creatPublishcloseDialog">
      <el-form :model="ruleForm" label-position="right" label-width="130px" ref="publishDialog" :rules="grayUserGroupRules">
        <el-form-item label="发布类型">
          <el-radio-group v-model="pulishType">
            <el-radio label="灰度"></el-radio>
            <el-radio label="正式"></el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否强制升级">
          <el-radio-group v-model="isForce">
            <el-radio label="是"></el-radio>
            <el-radio label="否"></el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- <el-form-item label="发布模型">
          <el-radio-group v-model="grayType">
            <el-radio label="特定用户灰度"></el-radio>
          </el-radio-group>
        </el-form-item> -->
        <!-- 特定用户灰度 -->
        <!-- <template v-if="grayType === '特定用户灰度'"> -->
          <el-form-item label="灰度用户组配置 : " prop="whiteItemId">
            <el-select v-model="ruleForm.whiteItemId" placeholder="请选择灰度用户组" @change="selectGet" size="mini" popper-class="zIndex-popper">
              <el-option v-for="item in whiteArr" :key="item.id" :label="item.groupName" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="升级提示信息 : ">
            <el-input type="textarea" v-model="HintMessage" :rows="1"></el-input>
          </el-form-item>
          <el-form-item label="发布描述 : ">
            <el-input type="textarea" v-model="PublishDescription" :rows="1"></el-input>
          </el-form-item>
        <!-- </template> -->
        <div class="form-buttons">
          <el-button @click="creatPublishcloseDialog" size="mini">关闭</el-button>
          <el-button type="primary" @click="publishSubmitForm" size="mini">确定</el-button>
        </div>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
  import VToolbar from '../../comm/iToolbar/iToolbar'
  // import VDialog from '../../comm/iDialog/iDialog'
  import rules from '../../js/formRules'
  import api from '../../../../api/url'
  import ajax from '../../../../api/ajax/ajax'
  import QRcode from 'qrcode'
  export default {
    components: {
      VToolbar
      // VDialog
    },
    filters: {
      capitalize (val) {
        let date = new Date(val)
        let Y = date.getFullYear() + '-'
        let M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-'
        let D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' '
        let H = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':'
        let m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':'
        let s = date.getSeconds() < 10 ? '0' + (date.getSeconds()) : date.getSeconds()
        return Y + M + D + H + m + s
      },
      publishT (val) {
        switch (val) {
          case '0':
            return '待发布'
          case '1':
            return '灰度发布'
          case '2':
            return '正式发布'
          default:
            return '后台意外的参数'
        }
      }
    },
    data () {
      return {
        publishVisible: false, // 创建发布弹窗是否显示
        packVisible: false, // 新建包弹框
        // creatData: {},
        whiteItemName: '',
        // whiteItemId: '',
        whiteArr: null, // 创建发布任务的“白名单灰度”选项的白名单配置
        sysType: 'Android', // 新建发布包弹框选择系统
        grayType: '特定用户灰度', // 创建发布任务的灰度类型选择
        versionType: '正式版',
        grayEndTime: '',
        HintMessage: '',
        PublishDescription: '',
        iosPublishPackUrl: '',
        currentRowData: [], // 点击发布那一栏的数据
        btnName: [{
          text: '新增版本'
        }],
        ruleForm: {
          whiteItemId: ''
        },
        tableData: [], // 表格数据
        pulishType: '灰度',
        isForce: '是',
        fileListForA: [], // 安卓fileList
        fileListForI: [], // ios fileList
        addPublishPack: { // 表单里输入框值
          ClientVersionId: '', //
          ClientVersionName: '',
          ClientType: '',
          IsForceUpdate: '1',
          fileListForA: [],
          fileListForI: []
        },
        addPubsishPackRules: rules.addPubsishPack, // 添加发布包的校验-android
        grayUserGroupRules: rules.grayUserGroupRules
      }
    },
    created () {
      this.getVersionList()
    },
    methods: {
      // 重置
      // 增加发布包的关闭
      addPublishCloseDialog () {
        this.packVisible = false
      },
      // 创建发布任务的关闭
      creatPublishcloseDialog () {
        this.publishVisible = false
        this.ruleForm.whiteItemId = ''
        this.$nextTick(() => {
          this.$refs.publishDialog.clearValidate()
        })
      },
      // 版本设置列表
      getVersionList () {
        ajax.get(api.VERSIONS).then(res => {
          let VerList = res.Version
          if (VerList !== undefined && VerList.length > 0) {
            // 第一个ios加标识
            for (let dd in VerList) {
              if (VerList[dd].ClientType === '1') {
                VerList[dd].IosFlag = true
                break
              }
            }
            // 第一个安卓加标识
            for (let dd in VerList) {
              if (VerList[dd].ClientType === '0') {
                VerList[dd].IosFlag = true
                break
              }
            }
            this.tableData = VerList
          } else {
            this.tableData = []
          }
        })
      },
      // 下拉选取value 和 label
      selectGet (val) {
        let obj = {}
        obj = this.whiteArr.find(item => {
          return item.groupId === val
        })
        this.whiteItemName = obj.groupName
      },
      // 创建发布任务
      creatPublishTasks (data) {
        this.publishVisible = true
        this.currentRowData = data
        // let arr = []
        // ajax.post(api.SEARCH_LIST_GROUP, {groupType: 'app', pageNo: 1, pageSize: 10000}).then(res => {
        //   arr = res.data.list.map(item => {
        //     return {'groupName': item.groupName, 'groupId': item.groupId}
        //   })
        //   this.whiteArr = arr
        // })
        ajax.post(api.GRAY_USER_GROUP_FILTER, {groupType: 'app', pageNo: 1, pageSize: 10000}).then(res => {
          // arr = res.data.list.map(item => {
          //   return {'groupName': item.groupName, 'groupId': item.groupId}
          // })
          // this.whiteArr = arr
          this.whiteArr = res.data
        })
      },
      // 新建包
      creatPack () {
        this.packVisible = true
      },
      // 删除版本
      delVersion (data) {
        this.$confirm('是否删除所选版本设置', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let params = { id: data.ClientVersionId }
          ajax.get(api.VERSIONDELETE, params).then(res => {
            if (res.Code === 0) {
              this.$message({
                type: 'success',
                message: '删除成功!'
              })
            }
          })
          ajax.post(api.DELETE_VERSION_GROUP, [data.ClientVersionId]).then(res => {
            if (res.Code === 0) {
              this.$message({
                type: 'success',
                message: '删除成功!'
              })
            }
            this.getVersionList()
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      },
      // 新增提交
      addSubmitForm () {
        if (this.addPublishPack.fileListForA.length > 0 || this.addPublishPack.fileListForI.length > 0) {
          this.$refs.fileForm.clearValidate()
        }
        this.$refs.addpg.validate(valid => {
          if (valid) {
              this.addPublishPack.ClientType = this.sysType === 'Android' ? 0 : 1
              this.addPublishPack.isAdd = '1'
              this.$refs.upload.submit() // 提交
              this.addPublishCloseDialog()
          }
        })
      },
      // 发布提交
      publishSubmitForm () {
        this.$refs.publishDialog.validate(valid => {
          if (valid) {
            let params = {
              // 特定用户
              ClientType: this.currentRowData.ClientType,
              ClientVersionId: this.currentRowData.ClientVersionId,
              ClientVersionName: this.currentRowData.ClientVersionName,
              ClientVersionURL: this.currentRowData.ClientVersionURL,
              PublishType: this.pulishType === '灰度' ? '1' : '2',
              IsForceUpdate: this.isForce === '是' ? '0' : '1',
              PublishMode: this.grayType === '特定用户灰度' ? '0' : '1',
              UserGroupId: this.ruleForm.whiteItemId,
              UserGroupName: this.whiteItemName,
              CreateTime: this.currentRowData.CreateTime,
              // 时间窗
              EndTime: '',
              Number: '',
              HintMessage: this.HintMessage,
              PublishDescription: this.PublishDescription
            }
            // let postParams = Object.assign(params, this.currentRowData)
            ajax.post(api.VERSIONUPDATE, params).then(res => {
              this.$message({
                type: 'success',
                message: res.msg
              })
            })
            ajax.post(api.INSERT_VERSION_GROUP, { versionIds: [params.ClientVersionId], groupId: params.UserGroupId }).then(res => {
              this.$message({
                type: 'success',
                message: res.msg
              })
            })
             this.creatPublishcloseDialog()
             this.getVersionList()
          }
        })
      },
      // 文件上传成功的回调
      successUpload (res, file, fileList) {
        this.$message({
          type: 'success',
          message: '添加成功'
        })
        fileList = []
        this.getVersionList()
      },
      uploadChangeA (file, fileList) {
        this.addPublishPack.fileListForA = fileList
        this.addPublishPack.ClientVersionId = file.name.split('.')[0]
        this.$refs.fileForm.clearValidate()
      },
      uploadChangeI (file, fileList) {
        this.addPublishPack.fileListForI = fileList
        this.$refs.fileForm.clearValidate()
      },
      // 二维码
      createQrc (ids, urlcode) {
        QRcode.toCanvas(document.getElementById(ids), urlcode, (err) => {
          if (err) console.log(err)
        })
      }
      // insertVersionGriop  {versionId: 'v5', groupId： 'sss'}
    }
  }
</script>
<style lang="stylus">
  #versionSetting
    height:100%
    .title
      height 60px
      padding 15px
      line-height 30px
      font-size 18px
      font-weight normal
      background #fff
    .table-cont
      height calc(100% - 68px)
      overflow: auto
      background: #fff
    .main-cont
      padding 10px 0 0 10px
      height calc(100% - 70px)
    .form-buttons
      text-align right
    .demo-table-expand
      font-size 0;
    .demo-table-expand label
      width 90px
    .demo-table-expand .el-form-item
      margin-right 0
      margin-bottom 0
      width 50%
</style>
